binary search combinatorics dp *1500

Please click on ads to support us..

Python Code:

def find(s):
    n = len(s)
    x = int(s)
    if (x < 10):
        return x
    ans = x // 10 - 1
    ans = ans + 9
    if (s[0] <= s[n-1]):
        ans = ans + 1
    return ans
 
l, r = map(int, input().split())
l = l - 1
l = str(l)
r = str(r)
count1 = find(l)
count2 = find(r)
print(count2 - count1)

C++ Code:

#include <iostream>
#include <cstring>

using namespace std;

typedef long long ll;

ll dp[10][20][2];

ll solve(string &num,int i,int j,int k)
{
    int n = num.size();
    
    if(dp[i][j][k]!=-1) return dp[i][j][k];
    
    if(j == 1){
       if(i == 0 && k == 1){
           return num[n-1] - '0';
       }
       if( i == 0 && k == 0 ) return 9;
       if ( k == 1 ) return i<=(num[n-1]-'0');
       
       return 1;
    }
    
    int ub = (k == 0)?9:num[n-j]-'0';
    ll ans = 0;
    
    for(int l = 0; l<=ub; l++)
    {  
       int f = (i == 0)?l:i;
       int tight = (k == 1)?l == ub:0;
       ans += solve(num,f,j-1,tight);
    }
    
    return dp[i][j][k] = ans;
    
}

int main()
{
    ll l1,r;
    
    cin>>l1>>r;
    
    ll l = l1-1;
    
    string rn = to_string(r);
    string ln = to_string(l);
    
    memset(dp,-1,sizeof(dp));
    
    ll fff = solve(rn,0,rn.size(),1);
    
    memset(dp,-1,sizeof(dp));
    ll lll = solve(ln,0,ln.size(),1);
    
    cout<<fff-lll;
}


Comments

Submit
0 Comments
More Questions

1593C - Save More Mice
1217. Minimum Cost to Move Chips to The Same Position
347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference
1619B - Squares and Cubes